/**
 * 使用axios发送ajax请求
 * 1、安装并引入
 *  npm install axios.min --save||直接下载axios.min.js
 * 2、基本用法:
 *     + axios([
 *         method:"post",
 *         url:"",
 *         data:{},//可选
 *         responseType:"",//可选
 *         headers:{"":"","":""...}//可选
 *     ]).then(function(data){
  *
  *     });
 *     + axios.request(config)
 *     + axios.get(url[,config])
 *     + axios.delete(url[,config])
 *     + axios.head(url[,config])
 *     + axios.post(url[,data[,config]])
 *     + axios.put(url[,data[,config]])
 *     + axios.patch(url[,data[,config]])
 *
 * */
import axios from 'axios'
import qs from 'qs'
axios.defaults.timeout = 5000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

//POST传参序列化
axios.interceptors.request.use((config) => {
    config.withCredentials = true;

    if (config.method === 'post') {
        config.data = qs.stringify(config.data);
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});

//code状态码200判断
axios.interceptors.response.use((res) => {
    if (res.status != '200') {
        $.Utils.showBarrage(res.statusText);
        return Promise.reject(res);
    }

    if (res.data.code == 'success') {
        return res.data;
    } else {
        if (res.data.code == "err_not_auth" || res.data.code == "err_not_login") {
            $.Utils.showBarrage(res.data.msg || "请重新登录", 1000, function () {
                window.top.location.href = "../index.html";
            });
        } else {
            $.Utils.showBarrage(res.data.msg);
        }
        return Promise.reject(res);
    }
    return res;
}, (error) => {
    $.Utils.showBarrage("网络异常");
    return Promise.reject(error);
});

global = global || {};
global.axios = axios;

export default {
    install: function (Vue, options) {
        Vue.prototype.$axios = axios;
        Vue.prototype.axios = axios;
    }
};

